#!/bin/bash
#backupSchool
if [ ! -n "$1" ] || [ ! -n "$2" ] || [ ! -n "$3" ]; then
        echo 'ERROR! backupSchool, 必要参数不能为空！参数要求: schoolCode, version, mysqlRootPass'
        exit -1;
fi

schoolCode=$1
version=$2
mysqlRootPass=$3
nasPath=/var/nas
schoolCodeLowerCase=`echo $schoolCode | tr '[A-Z]' '[a-z]'`
BX_HOME=$nasPath/$schoolCode
if [ ! -d "$BX_HOME" ]; then
        echo "ERROR! backupSchool, $schoolCode not found."
        exit 0;
fi


mysqlMasterPod=`kubectl get pod -owide | grep $schoolCodeLowerCase-mysql|grep -v "$schoolCodeLowerCase-mysql-s-"`
if [ -z "$mysqlMasterPod" ]; then
	echo "ERROR! backupSchool, $schoolCode-mysql not found."
	exit 0;
fi

mysqlMasterPodName=`echo $mysqlMasterPod|awk '{print $1}'`
mysqlMasterHost=`echo $mysqlMasterPod|awk '{print $6}'`
#只读模式
mysqlReadonly=`kubectl exec $mysqlMasterPodName /bin/bash /usr/local/data/mysql-flush-readonly.sh $mysqlRootPass 1`
if [ "$mysqlReadonly" != 'ON' ]; then
	echo "ERROR! mysql-flush-readonly error, result: $mysqlReadonly"
	exit 0
fi
#复制文件
cp -r $BX_HOME/config $BX_HOME/config-$version
ssh root@$mysqlMasterHost "cp -r /var2/mysql/$schoolCode /var2/mysql/$schoolCode-$version"
#解除只读
mysqlReadonly=`kubectl exec $mysqlMasterPodName /bin/bash /usr/local/data/mysql-flush-readonly.sh $mysqlRootPass 0`
if [ "$mysqlReadonly" != 'OFF' ]; then
	echo "ERROR! mysql-flush-readonly error, result: $mysqlReadonly"
	exit 0
fi
echo "SUCCESS! ending backup $schoolCode ."